// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database({
  throwOnNotFound: false
});
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var date = event.date;
  var city = event.city;
  var des = event.des;
  var longitude = event.longitude;
  var latitude=event.latitude;
  var note = event.note;
  if (note == null){
    note = "";
  }
  

  const sufferer = await db.collection("suffererOrbit")
    .where(
      {
        city: city,
        date: date,
        location: _.geoNear({
          geometry: db.Geo.Point(longitude, latitude),
          maxDistance: 1000,
        })
      }
    ).get();
  var sdata = sufferer.data;

  if (sdata.length == 0 ) {
    await db.collection("myOrbit").add({
      data: {
        _openid: wxContext.OPENID,
        date: date,
        city: city,
        note:note,
        des:des,
        location: {
          type: 'Point',
          coordinates: [longitude, latitude]
        },
        dangerous: false,
      }
    })
    return { dangerous: false }
  } else {
    await db.collection("myOrbit").add({
      data: {
        _openid: wxContext.OPENID,
        date: date,
        city: city,
        des: des,
        note: note,
        location: {
          type: 'Point',
          coordinates: [longitude, latitude]
        },
        dangerous: true,
      }
    })
    return { dangerous: true }
  }
}